package xulong.com.weiyulinked.config;


import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import xulong.com.weiyulinked.controller.MessageRequest;
import xulong.com.weiyulinked.controller.MessageResponse;
import xulong.com.weiyulinked.mapper.MessageSessionMapper;
import xulong.com.weiyulinked.model.UserInfo;
import xulong.com.weiyulinked.model.message;

import java.io.IOException;

@Component
public class WebSocketConfig extends TextWebSocketHandler {

    @Autowired
    private OnlineUserManage onlineUserManage;

    @Autowired
    private MessageSessionMapper messageSessionMapper;
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        UserInfo user = (UserInfo) session.getAttributes().get("user");
        if (user == null) {
            System.out.println("用户信息为空");
            return;
        }
        System.out.println("连接成功");
        //将用户ID和session添加到在线用户列表中
        onlineUserManage.online(user.getId(), session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        System.out.println("收到消息"+message.toString());
        //1.先获取到用户信息
        UserInfo user = (UserInfo) session.getAttributes().get("user");
        if (user == null) {
            System.out.println("用户信息为空");
            return;
        }
        //2.针对请求进行解析，将json转换成对象
        MessageRequest messageRequest = objectMapper.readValue(message.getPayload(), MessageRequest.class);
        //3.根据消息类型进行处理
        if (messageRequest.getType().equals("message")) {
            //4.进行转发消息
            transferMessage(user, messageRequest);
        }else {
            System.out.println("未知消息类型"+messageRequest.getType());
        }

    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("连接失败"+exception.toString());
        //连接失败后，将session从session列表中移除
        UserInfo user = (UserInfo) session.getAttributes().get("user");
        if (user == null) {
            System.out.println("用户信息为空");
            return;
        }
        //将用户ID和session从在线用户列表中移除
        onlineUserManage.offline(user.getId(), session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("连接关闭");
        //连接关闭后，将session从session列表中移除
        UserInfo user = (UserInfo) session.getAttributes().get("user");
        if (user == null) {
            System.out.println("用户信息为空");
            return;
        }
        //将用户ID和session从在线用户列表中移除
        onlineUserManage.offline(user.getId(), session);
    }

    public void transferMessage(UserInfo fromUser, MessageRequest messageRequest) throws IOException {
        //1.构造响应对象
        MessageResponse messageResponse = new MessageResponse();
        messageResponse.setFromId(fromUser.getId());
        messageResponse.setFromName(fromUser.getUsername());
        messageResponse.setSessionID(Integer.parseInt(messageRequest.getSessionID()));
        messageResponse.setContent(messageRequest.getContent());
        messageResponse.setPostTime(messageRequest.getPostTime());
        //2.将响应对象转换为json字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(messageResponse);
        //3.根据sessionID获取到用户信息
        int friendId = messageSessionMapper.selectFriendIdBySessionId(Integer.parseInt(messageRequest.getSessionID()), fromUser.getId());
        //4.发送消息
        WebSocketSession friendSession = onlineUserManage.getSession(friendId);
        if (friendSession != null) {
            //如果好友在线，就发送消息
            friendSession.sendMessage(new TextMessage(json));
        }
        //5.给自己也发一份，方便前端显示
        onlineUserManage.getSession(fromUser.getId()).sendMessage(new TextMessage(json));
        //6.保存消息
        //6.1构造message表
        message message = new message();
        message.setFromId(fromUser.getId());
        message.setFromName(fromUser.getUsername());
        message.setSessionId(Integer.parseInt(messageRequest.getSessionID()));
        message.setContent(messageRequest.getContent());
        message.setPostTime(messageRequest.getPostTime());
        //6.2插入到数据库
        messageSessionMapper.insertMessage(message);
    }
}
